#!/usr/bin/env python
# -*- coding: utf-8 -*-import requests
import requests
API_ENDPOINT = "https://api.remove.bg/v1.0/removebg"
class RemoveBg():

    def __init__(self, api_key):
        self.__api_key = api_key


    # 文件大小：最大 12 MB
    # img_file_path ： 需要抠图的图片路径
    # out_file_path ： 扣好的图片保存路径
    # size参数的解释如下
    # size: `'auto'` = highest available resolution, `'preview'`|`'small'`|`
    # 'regular'` = 0.25 MP, `'medium'` = 1.5 MP, `'hd'` = 4 MP, `'full'`|`'4k'` = original size)
    # bg_color 实例：  "green"背景绿色       "yellow"背景黄色    None无背景（这个None不用引号，其他颜色要引号） 
    def remove_background_from_img_file(self, img_file_path, out_file_path, size="auto", bg_color=None):
        # Open image file to send information post request and send the post request
        img_file = open(img_file_path, 'rb')
        response = requests.post(
            API_ENDPOINT,
            files={'image_file': img_file},
            data={
                'size': size,
                'bg_color': bg_color
            },
            headers={'X-Api-Key': self.__api_key})
        response.raise_for_status()
        self.__output_file__(response, out_file_path)

        # Close original file
        img_file.close()

    def __output_file__(self, response, new_file_name):
        # If successful, write out the file
        if response.status_code == requests.codes.ok:
            with open(new_file_name, 'wb') as removed_bg_file:
                removed_bg_file.write(response.content)
                print("抠图成功：" + new_file_name)
        # Otherwise, print out the error
        else:
            error_reason = response.json()["errors"][0]["title"].lower()
            print.error("抠图保存失败，文件名是： %s 。。。原因是： %s", new_file_name, error_reason)



              